<?php
namespace app\base\controller;

use app\base\model\SliderModel;
use app\common\base\BasicRest;
use think\Image;
use think\Request;

class Slider extends BasicRest
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index(){
        $subjectData = SliderModel::where(['IsDeleted'=>0])->select();
        if($subjectData) return res_success($subjectData);
        return res_fail('未找到信息');
    }

    #设为轮播
    public function setSlider(Request $request){
        $id = $request->get('id');
        $data = SliderModel::get($id);
        if($data->OnShow==0){
            $sliderNumber = SliderModel::where(['IsDeleted'=>0,'OnShow'=>1])->count();
            if($sliderNumber>=5){
                return res_fail('only5');
            }else{
                $res = SliderModel::where('Id',$id)->update(['OnShow'=>1]);
            }
        }else{
            $res = SliderModel::where('Id',$id)->update(['OnShow'=>0]);
        }
        if($res!== false) return res_success();
        return res_fail('修改失败');

    }

    #删除图片
    public function delete($id){
        $res = SliderModel::where('Id',$id)->update(['IsDeleted'=>'1']);
        if($res) return res_success();
        return res_fail('删除失败');
    }

    //登录页轮播图
    public function slider(){
        $subjectData = SliderModel::where(['IsDeleted'=>0,'OnShow'=>1])->select();
        if($subjectData) return res_success($subjectData);
        return res_fail('未找到信息');
    }

    #上传
    public function upload(Request $request){
        $file=$request->file('file');
        $info=$file->move(ROOT_PATH . 'public' . DS .'res');
        $name = $info->getSavename();
        $filename = strstr($info->getFilename(),'.',TRUE);
        //生成缩略图
        $image = Image::open(ROOT_PATH.'public\res\\'.$name);
        // 按照原图的比例生成一个最大为300*300的缩略图并保存为thumb.png
        $image->thumb(200,300)->save(ROOT_PATH.'public\res\thumb\\'.$filename.'thumb.png');
        //按比例生成轮播图
        $slider = Image::open(ROOT_PATH.'public\res\\'.$name);
        // 按照原图的比例生成一个最大为3000*300的缩略图并保存为thumb.png
        $slider->save(ROOT_PATH.'public\res\slider\\'.$filename.'slider.png');
        $data = [
            'Path'=>$filename.'slider.png',
            'ThumbPath'=>$filename.'thumb.png',
        ];
        $subjectData = SliderModel::create($data);
        if($subjectData) return res_success();
        return res_fail('上传失败');
    }
}